/**
 * JAVACC DEMO 1.0
 */
package com.apache.info.service.plugins;

import com.alibaba.druid.pool.DruidDataSource;
import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.database.datasource.ConnctionData;
import com.apache.database.datasource.DynamicDataSource;
import com.apache.info.entity.PubMetadata;
import com.apache.info.entity.PubSortInfo;
import com.apache.info.manager.InfoReleaseManager;
import com.apache.info.manager.PubMetadataManager;
import com.apache.info.manager.PubSortInfoManager;
import com.apache.info.util.MessageUtil;
import com.apache.tools.StrUtil;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * description:  动态创建表操作
 *
 * @author Hou Dayu 创建时间：2016-8-28
 */
public class DynamicCreateTablePluinImpl implements PluginConnector {
	protected Logger log = Logger.getLogger(getClass());
	private InfoReleaseManager infoReleaseManager;

	private PubMetadataManager pubMetadataManager;

	protected PubSortInfoManager pubSortInfoManager;

	/**
	 * TODO 动态创建表插件实现.
	 *
	 * @see PluginConnector#execute(ParamsVo)
	 */
	public Object execute(ParamsVo vo) throws Exception {
		PubSortInfo sort = (PubSortInfo) vo.getParams("sort");
		String sysName = StrUtil.doNull(sort.getSysName(), "plateform");
		String tableName = sort.getInfoTableName();
		log.info("create table [" + tableName + "] by sysName ["+sysName+"]");
		ParamsVo<PubMetadata> met = new ParamsVo<PubMetadata>();
		PubMetadata pm = new PubMetadata();
		pm.setSortId(sort.getSortId());
		met.setObj(pm);
		List<PubMetadata> list = pubMetadataManager.getList(met);
		if (!Validator.isEmpty(list)) {
			DruidDataSource bds = DynamicDataSource.getInstance().getDataSource(sysName);//ConnctionData.getInstance().getDataSource(sort.getSysName());
			//			if (null == bds) {
			//				bds = ConnctionData.getInstance().getDataSource("plateform");
			//			}
			String dbType = MessageUtil.getDatabastType(sysName, bds.getDriverClassName());
			log.info("this operation dbType ["+dbType+"]");
			String sql = "";
			if ("oracle".equals(dbType)) {
				sql = createTableSqlForOracle(list, sort.getInfoTableName());
			} else if ("sqlserver".equals(dbType)) {
				sql = createTableSqlForSqlserver(list, sort.getInfoTableName());
			} else if ("mysql".equals(dbType)) {
				sql = createTableSqlForMySql(list, sort.getInfoTableName());
			}
			log.info("this operation dyncSql ["+sql+"]");
			ParamsVo pvo = new ParamsVo();
			pvo.setParams("dyncSql", sql);
			pvo.setParams("sort", sort);

			boolean mark =false;
			try {
				Connection con = bds.getConnection();
				mark = ConnctionData.getInstance().execute(con, sql);
			}catch (SQLException e){
				DynamicDataSource.getInstance().removeDataSource(sysName);
				return false;
			}
			//DynamicDataSourceHolder.putDataSource(Validator.getDefaultStr("", "default"));
			// if (mark) {
			ParamsVo<PubSortInfo> svo = new ParamsVo<PubSortInfo>();
			sort.setSortStatus("1");
			svo.setObj(sort);
			pubSortInfoManager.editInfo(svo);
			// }
			// return infoReleaseManager.editInfo(pvo);
			return mark;
		}
		return true;
	}

	/**
	 * description: oracle sql
	 */
	private String createTableSqlForOracle(List<PubMetadata> list, String tableName) {
		StringBuffer sql = new StringBuffer("create table " + tableName + "(");
		String pk = "";
		String pks = "";
		for (PubMetadata pm : list) {
			if ("F".equals(pm.getReserved2()))
				continue;
			sql.append(" " + pm.getDataShortName() + " ");
			if ("1".equals(pm.getDataType()) || "2".equals(pm.getDataType())) {
				sql.append(" number(" + pm.getDataLength() + ") ");
			} else if ("3".equals(pm.getDataType())) {
				sql.append(" number(" + pm.getDataLength() + ",2) ");
			} else if ("4".equals(pm.getDataType())) {
				sql.append(" char(" + pm.getDataLength() + ") ");
			} else if ("6".equals(pm.getDataType())) {
				sql.append(" date ");
			} else {
				sql.append(" varchar2(" + pm.getDataLength() + ") ");
			}

			if ("1".equals(pm.getDataRestrict())) {
				sql.append(" not null ");
				pk = pm.getDataShortName();
			} else if ("2".equals(pm.getDataRestrict())) {
				sql.append(" not null ");
			} else if ("4".equals(pm.getDataRestrict())) {
				sql.append(" not null ");
				pks += "," + pm.getDataShortName();
			}
			sql.append(",");
		}
		if (Validator.isNotNull(pk)) {
			sql.append("primary key(" + pk + ")");
		} else if (Validator.isNotNull(pks)) {
			sql.append("primary key(" + pks.substring(1) + ")");
		}
		sql.append(")");
		return sql.toString();
	}

	/**
	 * description: sqlserver sql
	 */
	private String createTableSqlForSqlserver(List<PubMetadata> list, String tableName) {
		StringBuffer sql = new StringBuffer("create table " + tableName + "(");
		String pk = "";
		String pks = "";
		for (PubMetadata pm : list) {
			sql.append(" " + pm.getDataShortName() + " ");
			if ("1".equals(pm.getDataType())) {
				sql.append(" int ");
			} else if ("2".equals(pm.getDataType())) {
				sql.append(" bigint ");
			} else if ("3".equals(pm.getDataType())) {
				sql.append(" float(" + pm.getDataLength() + ")");
			} else if ("4".equals(pm.getDataType())) {
				sql.append(" char(" + pm.getDataLength() + ") ");
			} else if ("6".equals(pm.getDataType())) {
				sql.append(" datetime ");
			} else {
				sql.append(" varchar(" + pm.getDataLength() + ") ");
			}

			if ("1".equals(pm.getDataRestrict())) {
				sql.append(" not null ");
				pk = pm.getDataShortName();
			} else if ("2".equals(pm.getDataRestrict())) {
				sql.append(" not null ");
			} else if ("4".equals(pm.getDataRestrict())) {
				sql.append(" not null ");
				pks += "," + pm.getDataShortName();
			}
			sql.append(",");
		}
		if (Validator.isNotNull(pk)) {
			sql.append("primary key(" + pk + ")");
		} else if (Validator.isNotNull(pks)) {
			sql.append("primary key(" + pks.substring(1) + ")");
		}
		sql.append(")");
		return sql.toString();

	}

	/**
	 * description: mysql sql
	 */
	private String createTableSqlForMySql(List<PubMetadata> list, String tableName) {
		StringBuffer sql = new StringBuffer("create table " + tableName + "(");
		String pk = "";
		String pks = "";
		for (PubMetadata pm : list) {
			sql.append(" " + pm.getDataShortName() + " ");
			if ("1".equals(pm.getDataType())) {
				sql.append(" int ");
			} else if ("2".equals(pm.getDataType())) {
				sql.append(" bigint ");
			} else if ("3".equals(pm.getDataType())) {
				sql.append(" float(" + pm.getDataLength() + ")");
			} else if ("4".equals(pm.getDataType())) {
				sql.append(" char(" + pm.getDataLength() + ") ");
			} else if ("6".equals(pm.getDataType())) {
				sql.append(" datetime ");
			} else if ("7".equals(pm.getDataType())) {
				sql.append(" longtext ");
			} else if ("8".equals(pm.getDataType())) {
				sql.append(" decimal(" + pm.getDataLength() + ") ");
			}  else {
				sql.append(" varchar(" + pm.getDataLength() + ") ");
			}

			if ("1".equals(pm.getDataRestrict())) {
				sql.append(" not null ");
				pk = pm.getDataShortName();
			} else if ("2".equals(pm.getDataRestrict())) {
				sql.append(" not null ");
			} else if ("4".equals(pm.getDataRestrict())) {
				sql.append(" not null ");
				pks += "," + pm.getDataShortName();
			}
			sql.append(",");
		}
		if (Validator.isNotNull(pk)) {
			sql.append("primary key(" + pk + ")");
		} else if (Validator.isNotNull(pks)) {
			sql.append("primary key(" + pks.substring(1) + ")");
		}
		sql.append(")");
		return sql.toString();
	}

	public void setInfoReleaseManager(InfoReleaseManager infoReleaseManager) {
		this.infoReleaseManager = infoReleaseManager;
	}

	public void setPubMetadataManager(PubMetadataManager pubMetadataManager) {
		this.pubMetadataManager = pubMetadataManager;
	}

	/**
	 * pubSortInfoManager.
	 *
	 * @param pubSortInfoManager the pubSortInfoManager to set
	 */
	public void setPubSortInfoManager(PubSortInfoManager pubSortInfoManager) {
		this.pubSortInfoManager = pubSortInfoManager;
	}

}
